define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template', 'jquery-jqprint', 'jquery-migrate','vue'], function ($, undefined, Backend, Table, Form, Template, Jqprint, Migrate,Vue) {
    var Controller = {
        index: function () {

            // return chatFun; 1.0.8升级 注释不明使用方式
            Table.api.init({
                extend: {
                    index_url: 'wanlshop/order/index' + location.search,
                    add_url: '',
                    edit_url: '',
                    del_url: 'wanlshop/order/del',
                    multi_url: 'wanlshop/order/multi',
                    table: 'wanlshop_order',
                }
            });
            var table = $("#table");
            Template.helper("Moment", Moment);
            Template.helper("cdnurl", function(image) {
                return Fast.api.cdnurl(image);
            });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                templateView: true,
                // showExport: true,  //打开导出
                // exportDataType: 'basic',
                // showToggle: true,
                // showColumns: true,
                checkboxHeader:true,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'user.nickname', title: __('User.nickname'), align: 'left', formatter: Table.api.formatter.search},
                        {field: 'order_no', title: __('Order_no')},
                        {field: 'pay.trade_no', title: __('支付订单号')},
                        {field: 'outtrades.out_trade_no', title: __('第三方支付订单号')},
                        {field: 'outtrade', title: __('第三方支付订单号'),formatter: function (value, row, index) {
                                if (row.outtrade[0]){
                                    return row.outtrade[0].out_trade_no;
                                }
                                return ''
                            },searchable:false},
                        {field: 'outtrade_mch_names', title: __('商户名称(多)'),searchable:false},
                        {field: 'address.mobile', title: __('收货人手机号')},
                        {field: 'express_no', title: __('Express_no')},
                        {field: 'state', title: __('State'), searchList: {"1":__('State 1'),"2":__('State 2'),"3":__('State 3'),"4":__('State 4'),"6":__('State 6'),"7":__('State 7')}, formatter: Table.api.formatter.normal},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'paymenttime', title: __('Paymenttime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'delivertime', title: __('Delivertime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'dealtime', title: __('Dealtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'status', title: __('Status'), searchList: {"normal":__('Normal'),"hidden":__('Hidden')}, formatter: Table.api.formatter.status},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
            //点击详情
            $(document).on("click", ".detail[data-id]", function () {
                Backend.api.open('wanlshop/order/detail/id/' + $(this).data('id'), __('查看详情'),{area:['1200px', '780px']});
            });
            //查看退款
            $(document).on("click", ".refund[data-id]", function () {
                Backend.api.open('wanlshop/refund/detail/ids/' + $(this).data('id'), __('查看退款'));
            });
            // 查看评论
            $(document).on("click", ".comment[data-id]", function () {
                Backend.api.open('wanlshop/comment/detail/order_id/' + $(this).data('id'), __('查看评论'));
            });
            // 查看退款
            $(document).on("click", ".btn-selected", function () {
                Backend.api.open('wanlshop/refund/detail/order_id/' + $(this).data('id'), __('查看退款'));
            });
            // 即时沟通
            $(document).on("click", ".btn-delone", function () {
                console.log(window);
                chatFun({
                    user_id: $(this).data('id'),
                    nickname: $(this).data('name'),
                    avatar: $(this).data('avatar'),
                    isOnline: 1
                }, 'fun');
            });
            // 发货 & 批量发货
            $(document).on("click", ".btn-delivery", function () {
                if($(this).data('id')){
                    Backend.api.open('wanlshop/order/delivery/ids/' + $(this).data('id'), __('发货'),{area:['1000px', '700px']});
                }else{
                    Backend.api.open('wanlshop/order/delivery/ids/' + Table.api.selectedids(table), __('批量发货'),{area:['1000px', '700px']});
                }
            });
            //execl导出
            $(document).on("click", ".export", function () {
                console.log(Vue)
                Backend.api.open('wanlshop/order/export', __('Execl导出订单'),{area:['1000px', '700px']});
            })
            $(document).on("click", ".information", function () {
                Backend.api.open('wanlshop/order/information', __('Execl导入发货'),{area:['1000px', '700px']});
            })
            //修改状态
            $(document).on("click", ".xiugai", function () {
                // 构建API请求URL
                var apiUrl = '/api/order/order/xiu?id=' + $(this).data('id');

                // 发起Fetch API请求
                fetch(apiUrl)
                    .then(response => {
                        if (response.ok) {
                            return response.json(); // 解析响应数据
                        } else {
                            throw new Error('API请求失败');
                        }
                    })
                    .then(data => {
                        // 在这里处理从API返回的数据
                        console.log(data);
                        // 请求成功后刷新当前页面
                        // location.reload(true);
                        table.bootstrapTable('refresh');
                    })
                    .catch(error => {
                        console.error('API请求出错:', error);
                    });
            });
            // 打印 & 批量打印订单 自动关闭窗口parent.Layer.closeAll();
            $(document).on("click", ".btn-invoice", function () {
                if($(this).data('id')){
                    Backend.api.open('wanlshop/order/invoice/ids/' + $(this).data('id'), __('查看发货单'),{area:['1100px', '750px']});
                }else{
                    Backend.api.open('wanlshop/order/invoice/ids/' + Table.api.selectedids(table), __('批量查看发货单'),{area:['1100px', '750px']});
                }
            });
            // 查询物流状态
            $(document).on("click", ".kuaidisub[data-id]", function () {
                Backend.api.open('wanlshop/order/relative/id/' + $(this).data('id'), __('快递查询'),{area:['800px', '600px']});
            });
            // 提交云面单
            $(document).on("click", ".btn-express", function () {
                Layer.alert('订单' + JSON.stringify(Table.api.selectedids(table)) + '无法云打印,因为API接口维护中...');
            });
        },
        comment: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'wanlshop/comment/index' + location.search,
                    add_url: '',
                    edit_url: '',
                    del_url: '',
                    multi_url: '',
                    table: 'wanlshop_goods_comment',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                searchFormVisible:true,
                // showToggle: true,
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'user.nickname', title: __('User.nickname'), formatter: Table.api.formatter.search},
                        {field: 'goods.title', title: __('goods.title'), searchable: false},
                        {field: 'order_type', title: __('Order_type'), searchList: {"goods":__('Order_type goods'),"groups":__('Order_type groups'),"seckill":__('Order_type seckill')}, formatter: Table.api.formatter.normal},
                        {field: 'state', title: __('States'), searchList: {"0":__('States 0'),"1":__('States 1'),"2":__('States 2')}, formatter: Table.api.formatter.normal},
                        {field: 'images', title: __('Images'), events: Table.api.events.image, formatter: Table.api.formatter.images},
                        {field: 'score', title: __('Score'), operate:'BETWEEN'},
                        {field: 'score_describe', title: __('Score_describe'), operate:'BETWEEN'},
                        {field: 'score_service', title: __('Score_service'), operate:'BETWEEN'},
                        {field: 'score_deliver', title: __('Score_deliver'), operate:'BETWEEN'},
                        {field: 'score_logistics', title: __('Score_logistics'), operate:'BETWEEN'},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'status', title: __('Status'), searchList: {"normal":__('Normal'),"hidden":__('Hidden')}, formatter: Table.api.formatter.status},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'detail',
                                    title: function (row) {
                                        return `查看 ${__('Order_type ' + row.order_type)} 评论`;
                                    },
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    icon: 'fa fa-eye',
                                    url: 'wanlshop/comment/detail'
                                },
                            ],formatter: Table.api.formatter.operate,
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        invoice: function () {
            $(document).on("click", ".btn-embossed", function () {
                $("#print_html").jqprint();
                $(".btn-embossed").text("初始化打印..");
                setTimeout(function() {
                    parent.Layer.closeAll();
                },1000);
            });
        },
        relative: function () {

        },
        detail: function () {
            // 查询物流状态
            $(document).on("click", ".kuaidisub[data-id]", function () {
                Backend.api.open('wanlshop/order/relative/id/' + $(this).data('id'), __('快递查询'),{area:['800px', '600px']});
            });
        },
        delivery: function () {
            Controller.api.bindevent();
        },
        export: function (){
            new Vue({
                el: "#app",
                data() {
                    return {
                        DateAlert:'',
                        stateAlert:'',
                        selectedDate:null,
                        state:null,
                        good:'',
                        goods:[],
                        options: [{
                            value: '1',
                            label: '待支付'
                        }, {
                            value: '2',
                            label: '待发货'
                        }, {
                            value: '3',
                            label: '待收货'
                        }, {
                            value: '4',
                            label: '待评论'
                        }, {
                            value: '5',
                            label: '售后订单(已弃用)'
                        },{
                            value: '6',
                            label: '已完成'
                        },{
                            value: '7',
                            label: '已取消'
                        }
                        ],
                    }
                },
                mounted() {
                    this.getGoods();
                },
                methods: {
                    async getGoods(){
                        const hostname = window.location.hostname;
                        const url = 'https://'+ hostname
                        const api = '/api/execl/export/getGoods';
                        const apiUrl = url+api
                        const response = await fetch(apiUrl, {
                            method: 'GET',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                        });
                        if (response.ok) {
                            var	json = await response.json();
                            console.log(json.data)
                            this.goods = json.data
                        }
                    },
                    daochu(){
                        if (!this.state) {
                            this.stateAlert = '请选择状态！'
                        }
                        if(!this.selectedDate){
                            this.DateAlert = '请选择时间！'
                        }
                        if(this.selectedDate&&this.state){
                            this.exportExecl()
                        }


                    },
                    async exportExecl(){
                        try {
                            const hostname = window.location.hostname;
                            const url = 'https://'+ hostname
                            const api = '/api/execl/export/order';
                            const apiUrl = url+api
                            const requestData = {
                                date: this.selectedDate,
                                state: this.state,
                                good:this.good
                            };
                            const response = await fetch(apiUrl, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                },
                                body: JSON.stringify(requestData),
                            });
                            if (response.ok) {
                                var	json = await response.json();
                                console.log(json.data)
                                window.location.href = json.data;
                            }
                        } catch (error) {
                            console.log(error)
                            alert('请稍后重试或联系开发者');
                        }
                    },
                    displaySelectedDate(){
                        var datePicker = document.getElementById('datepicker');
                        var selectedDate = datePicker.value;
                        var displayElement = document.getElementById('selectedDate');
                    }
                },
            });
        },
        information: function (){
            new Vue({
                el: "#information",
                data() {
                    return {
                        kuaidi:null,
                        kuaidiList:[],
                        kuaidiShow:false,
                        kauidiAlert:null,
                        selectedFiles: [],
                        uploadProgressVisible: false,
                        uploadPercentage: 0,
                        fail:[],
                        failShow:false,
                    }
                },
                mounted() {
                    this.getKuaidi()
                },
                methods: {
                    handleFileChange(event) {
                        this.selectedFiles = Array.from(event.target.files);
                        if (this.selectedFiles.length > 0) {
                            this.uploadProgressVisible = true;
                            let percentage = 0;
                            const interval = setInterval(() => {
                                percentage += 10;
                                this.uploadPercentage = percentage;
                                if (percentage >= 100) {
                                    clearInterval(interval);
                                    this.uploadProgressVisible = false;
                                }
                            }, 500);
                        }
                    },
                    confirm(){
                        if (!this.kuaidi){
                            this.kuaidiShow = true;
                            this.kauidiAlert = '请选择快递！'
                        }else{
                            this.kuaidiShow = false;
                            this.uploadFiles()
                        }

                    },
                    async uploadFiles(){
                        try {
                            const formData = new FormData();
                            this.selectedFiles.forEach(file => {
                                formData.append('file', file);
                            });
                            formData.append('kuaidi', this.kuaidi);
                            const hostname = window.location.hostname;
                            const url = 'https://'+ hostname
                            const response = await fetch(url+'/api/execl/export/newInformation', {
                                method: 'POST',
                                body: formData,
                            });
                            if (response.ok) {
                                var	json = await response.json();
                                if(json.code == 1){
                                    this.failShow = true
                                    this.fail = json.data
                                    console.log(this.fail)
                                }else{
                                    alert(json.msg)
                                }
                            }
                        } catch (error) {
                            console.log(error)
                            alert('请稍后重试或联系开发者');
                        }
                    },
                    async getKuaidi(){
                        const hostname = window.location.hostname;
                        const url = 'https://'+ hostname
                        const apiUrl = url+'/api/execl/export/kuaidi'
                        const response = await fetch(apiUrl, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                        });
                        if (response.ok) {
                            var	json = await response.json();
                            if(json.code == 1){
                                this.kuaidiList = json.data
                                console.log(this.kuaidiList)
                            }
                        }
                    }
                },
            });
        },
        api: {
            bindevent: function () {
                console.log('点击了')
                Form.api.bindevent($("form[role=form]"));
            }
        },
    };
    return Controller;
});